//
//  LXProperty.m
//  LXModelExtensionExample
//
//  Created by imera on 16/5/19.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXProperty.h"
#import <CoreData/CoreData.h>

@interface LXProperty()

@property (nonatomic, strong) NSArray *foundation;

@end

@implementation LXProperty

- (NSArray *)foundation
{
    if (_foundation == nil) {
        _foundation = @[[NSArray class],
                        [NSMutableArray class],
                        [NSDictionary class],
                        [NSMutableDictionary class],
                        [NSString class],
                        [NSMutableString class],
                        [NSData class],
                        [NSDate class],
                        [NSURL class],
                        [NSError class],
                        [NSNumber class],
                        [NSValue class],
                        [NSAttributedString class]];
    }
    return _foundation;
}

+ (instancetype)initWithProperty:(objc_property_t)property
{
    return [[self alloc] initWithProperty:property];
}

- (instancetype)initWithProperty:(objc_property_t)property
{
    return [[self init] setWithProperty:property];
}

#pragma mark - 对象初始化
- (instancetype)setWithProperty:(objc_property_t)property
{
    //1.获取属性名称
    const char *name = property_getName(property);
    self.name = [NSString stringWithUTF8String:name];
    
    //2.判断属性类型
    const char *attr = property_getAttributes(property);
    NSString *attrStr = [NSString stringWithUTF8String:attr];
    self.isModelObject = [self isModelObject:attrStr];
    
    return self;
}

#pragma mark - 判断是否为模型数据类型
/**
 *  判断是否为模型数据类型
 *
 *  @param attrs 成员属性描述
 *
 *  @return YES（模型数据），NO（不是模型数据）
 */
- (BOOL)isModelObject:(NSString *)attrs
{
    NSString *className = [self subStringInQuote:attrs];
    
    if (className == nil) { //基本数据类型
        return NO;
    }else{
        Class class = NSClassFromString(className);
        if (class == [NSObject class] || class == [NSManagedObject class]) {
            return NO;
        }
        
        NSUInteger count = self.foundation.count;
        for (int i=0; i<count; i++) {
            if ([class isSubclassOfClass:self.foundation[i]]) { //foundation框架中的数据类型
                return NO;
            }
        }
    }
    
    self.modelClass = NSClassFromString(className);
    return YES;
}

#pragma mark -  截取属性类型
- (NSString *)subStringInQuote:(NSString *)str
{
    NSRange start = [str rangeOfString:@"T@\"" options:NSAnchoredSearch];
    NSRange end = [str rangeOfString:@"\"," options:NSBackwardsSearch];
    if (start.location != NSNotFound && end.location != NSNotFound) {
        NSUInteger location = start.location + start.length;
        NSUInteger length = end.location - start.location - start.length;
        return [str substringWithRange:NSMakeRange(location, length)];
    }
    return nil;
}
@end
